package edu.umd.ion.wavemeter.server;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;

public class FiberSwitcherComm {
	CommPortIdentifier portId;
	SerialPort	      serialPort;
	OutputStream       outputStream;
	boolean	     IsOpen = false;
	String	portName;
	
	void open(String PortName) 
	throws NoSuchPortException, PortInUseException, IOException, UnsupportedCommOperationException {
		portName = PortName;
		portId = CommPortIdentifier.getPortIdentifier(portName);
		if (portId.getPortType() != CommPortIdentifier.PORT_SERIAL) throw new NoSuchPortException();
		serialPort = (SerialPort) portId.open("Wavemeter", 2000);
		outputStream = serialPort.getOutputStream();
		serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, 
				SerialPort.PARITY_NONE);	
		IsOpen = true;
	}
	 
	@SuppressWarnings("unchecked")
	void printPortNames() {
	    Enumeration<CommPortIdentifier> portList;
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
		    portId = portList.nextElement();
		    System.out.println("Found port " + portId.getName());
		}

	}
	
	public void writeln(String Message) throws IOException {
		outputStream.write(Message.getBytes());
		outputStream.flush();
	}
	
	public void write(String Message) throws IOException {
		outputStream.write(Message.getBytes());
	}
	
	public void write(byte[] bytes) throws IOException {
		outputStream.write(bytes);
	}

	public void write(byte bytes) throws IOException {
		outputStream.write(bytes);
	}
	
	public void flush() throws IOException {
		outputStream.flush();		
	}
	
	public void close(){
		serialPort.close();
		IsOpen = false;
	}
}




